package simpleservletcontainer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceProcessor {
	private static int BUFFER_SIZE = 1024;

	public void process(Request request, Response response) throws IOException {
		File file = null;
		if(request.getUri().equals("/")) {
			file = new File(HttpServer.WEB_ROOT+request.getUri()+"index.html");
		}else {
			file = new File(HttpServer.WEB_ROOT+request.getUri());
		}
		OutputStream output = response.getOutput();
		if(file.exists() && !file.isDirectory()) {
			FileInputStream input = new FileInputStream(file);
			// 头部
			String okHeader = "HTTP/1.1 200 OK \r\n\r\n";
			output.write(okHeader.getBytes());
			
			// 写入数据
			System.out.println("write...");
			byte[] bytes = new byte[BUFFER_SIZE];
			int ch = input.read(bytes);
			while(ch != -1) {
				output.write(bytes,0,ch);
				ch = input.read(bytes);
			}	
			System.out.println("write end");
		}else {
			// 文件不存在
			String err = "HTTP/1.1 404 File Not Found\r\n"
					+ "Content-Type: text/html\r\n"
					+ "Content-Length: 23\r\n"
					+ "\r\n"
					+ "<h1>File Not Found</h1>";
			output.write(err.getBytes());
		}
	}

}
